#pragma once
#include "DXAMLCommon.h"
#include "CXcpObjectBase.h"
#include "NoBaseClass.h"
#include "CXcpObjectThreadSafeAddRefPolicy.h"
#include "IInvalidateImageCacheCallback.h"
#include "ImageCache.h"

class ImageTaskDispatcher;
class SurfaceCache;
class CBitmapImage;
class CValueStore;



class ImageProvider :
	public CXcpObjectBase<NoBaseClass,CXcpObjectThreadSafeAddRefPolicy>,
	public IInvalidateImageCacheCallback
{

public: 
	static HRESULT Create(CCoreServices * pCore, ImageTaskDispatcher * pDispatcher, struct IPALAsyncImageFactory * pImageFactory, ImageProvider * * ppImageProvider);
	HRESULT GetEncodedImage(struct IPALMemory * pMemory, struct IPALImageSource * * ppEncodedImage);
	HRESULT GetImageFromUri(CBitmapImage * pBitmapImage, SurfaceCache * pSurfaceCache, CXString * pUri, struct IPALUri * pAbsoluteUri, const struct PALImageDecodeParams & params, enum GetImageOptions::Value options, struct IImageAvailableCallback * pCallback, ImageCache * * ppImageCache, struct IPALAbortableOperation * * ppGetOperation);
	HRESULT GetImage(struct IPALImageSource * pEncodedImage, const struct PALImageDecodeParams & params, enum GetImageOptions::Value options, struct IImageAvailableCallback * pCallback, struct IPALAbortableOperation * * ppGetOperation);
	HRESULT CleanupCaches();
	HRESULT Clear();

private: 
	ImageProvider();
	virtual ~ImageProvider();
	HRESULT Initialize(CCoreServices * pCore, ImageTaskDispatcher * pDispatcher, struct IPALAsyncImageFactory * pFactory);
	HRESULT GetImageCache(CXString * pUri, ImageCache * * ppCache);
	HRESULT AddImageCache(ImageCache * pCache);
	HRESULT RemoveImageCache(ImageCache * pCache);
	virtual HRESULT OnCacheInvalidated(ImageCache * pCache);
	HRESULT TriggerCacheCleanup();
	static void CleanupImageCacheStoreValue(CXString * pKey, void * value, void * extraData);
	CCoreServices * m_pCore;
	struct IPALAsyncImageFactory * m_pImageFactory;
	CValueStore * m_pStore;
	xvector<xref_ptr<ImageCache> > m_cachesForCleanup;
	XUINT32 m_hasCleanupTask;
	ImageTaskDispatcher * m_pDispatcher;
};